package com.cy.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.common.Constant;
import com.cy.entity.DiscussPost;
import com.cy.service.ELService;
import com.cy.service.LikeService;
import com.cy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: cy
 * @Date: 2022/02/10/15:50
 * @Description:
 */
@Controller
public class SearchController {

    @Autowired
    private UserService userService;

    @Autowired
    private ELService elService;

    @Autowired
    private LikeService likeService;


    @GetMapping(path = "/search")
    public String search(String keyword, Page page, Model model){
        // 搜索帖子
        org.springframework.data.domain.Page<DiscussPost> searchResult = elService.searchDiscussPost(keyword, (int) page.getCurrent() - 1, (int) page.getSize());

        // 聚合数据
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if(searchResult != null){
            searchResult.forEach(discussPost -> {
                Map<String, Object> map = new HashMap<>();

                // 帖子
                map.put("post", discussPost);
                // 作者
                map.put("user", userService.getById(discussPost.getUserId()));
                // 点赞数
                map.put("likeCount", likeService.findEntityLikeCount(Constant.ENTITY_TYPE_POST, discussPost.getId()));

                discussPosts.add(map);
            });
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);
        model.addAttribute("path", "/search?keyword="+ keyword);

        page.setTotal(searchResult.getTotalElements());
        return "/site/search";
    }

}
